import React from "react";
import logo from "@/assets/images/logo#000.png";
import wxGong from "@/assets/images/wxGong.png";
import NewLogo from "@/assets/images/NewLogo.jpg";

import printJs from "print-js";
import JsBarcode from "jsbarcode";
import { makeCode } from "@/utils/makeCode";

export function printOutLibraryOrder(dataSource) {
  let table = ''
  let dom = ''
  const info = `
  <div class='title'>${dataSource.libraryName}出库单</div>
  <div class="info">
      <div class="row">
          <div class="col">
              <span class="label">仓库名称:</span>
              <span class="val">${dataSource.libraryName ? dataSource.libraryName : ''}</span>
          </div>
          <div class="col">
              <span class="label">出库时间:</span>
              <span class="val">${dataSource.outLibraryTime ? dataSource.outLibraryTime : ''}</span>
          </div>
      </div>
      <div class="row">
          <div class="col">
              <span class="label">出库单号:</span>
              <span class="val">${dataSource.code ? dataSource.code : ''}</span>
          </div>
          <div class="col">
              <span class="label">对应单号:</span>
              <span class="val">${dataSource.dataCode ? dataSource.dataCode : ''}</span>
          </div>
      </div>
      <div class="row">
          <div class="col">
              <span class="label">备注:</span>
              <span class="val">${dataSource.remark ? dataSource.remark : ''}</span>      
          </div>
      </div>
  </div>`

  let head = `
          <tr>
          <td width="100px">物料编码</td>
          <td width="180px">物料名称</td>
          <td width="130px">规格型号</td>
          <td width="30px">数量</td>
          <td width="50px">单价</td>
          <td width="50px">金额</td>
          <td width="100px">仓库</td>
          <td width="110px">备注</td>
      </tr>`
  let resultDom = ''
  let countTotalResult = 0
  let priceTotalResult = 0
  // 混入合计，签字
  dataSource.stockOutLibraryInfoPrintVoList.push({
      countTotalResult,
      priceTotalResult
  })
  dataSource.stockOutLibraryInfoPrintVoList.push({
      zdrName: '',
      fahuoName: '',
      fuheName: '',
      shName: '',
  })
  const pageTotal = Math.ceil(dataSource.stockOutLibraryInfoPrintVoList.length / 6)


  dataSource.stockOutLibraryInfoPrintVoList.forEach((item, index) => {
      if (index % 6 === 0) {
          dom = `${info} `
          table = ''
          if (index === 0) {
              table = head
          }

      }

      if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
          table += `<tr>
              <td width="100px">合计：</td>
              <td width="180px"></td>
              <td width="130px"></td>
              <td width="30px">${countTotalResult}</td>
              <td width="50px"></td>
              <td width="50px">${priceTotalResult}</td>
              <td width="100px"></td>
              <td width="110px"></td>
          </tr>`
      } else if (index < dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
          countTotalResult += item.count ? item.count : 0
          priceTotalResult += parseFloat(item.totalPrice >= 0 ? ((item.totalPrice) / 100).toFixed(2) : 0)
          table += `<tr>
          <td width="100px"><div>${item.materialId ? item.materialId : ''}</div></td>
          <td width="180px"><div>${item.materialName ? item.materialName : ''}</div></td>
          <td width="130px"><div>${item.skuStr ? item.skuStr : ''}</div></div></td>
          <td width="30px"><div>${item.count ? item.count : 0}</div></td>
          <td width="50px"><div>${item.unitPrice ? ((item.unitPrice) / 100).toFixed(2) : 0}</div></td>
          <td width="50px"><div>${item.totalPrice?((item.totalPrice) / 100).toFixed(2) : 0}</div></td>
          <td width="100px"><div>${item.libraryName?item.libraryName:''}</div></td>
          <td width="110px"><div>${item.remark?item.remark:''}</div></td>
      </tr>`
      }
    
      if (index % 6 === 5 || index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
          dom += `  
          <div class="goodsInfo">
             <table border='1' cellPadding='0' cellSpacing='0' align="center">
                 <tbody>
                    ${table}
                 </tbody>
             </table>
          </div>
          <div class="pageNo">第${Math.ceil(index / 6)}/${pageTotal}页</div>
          `
          if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
              dom += `<div class="signName">
              <span>制单人：</span>
              <span>发货人：</span>
              <span>复核人：</span>
              <span>审核人：</span>
          </div>`
          }
          resultDom += dom
      }
  })
  let style = `@page { margin: 0; }
  @media print {
      body { padding: 20px 50px 20px 70px;}
              .printDom{
                  width:750px;
                  height:450px;
                  position:relative;
                  font-size:12px;
              }
              .title{
                  height:30px;
                  font-weight:600;
                  font-size:16px;
                  text-align:center;
                   padding-top:55px;
              }
              .title:first-child{
                  padding-top:0px;

              }
              .pageNo{
                  text-align:right;
                  margin-top:5px;


              }
              .signName{
                  height:40px;
                  display:flex;
                  align-items:center;
                  justify-content: space-between;
              }
              .signName span{
                  flex:1;
                 
              }
              .info{
                  height:60px;
              }
              .row{
                  display:flex;
                  align-items:center;
                  justify-content: space-between;
                  font-size:12px;
                  margin-bottom:5px;
              }
              .col{
                  flex:1;
              }
              .label{
                  width:100px;
                  text-align:right;
              }
              .val{
                  width:200px;
              }
            
              td{
                  height:50px;
                  font-size:12px;
                  text-align:center;
              }
              td div{
                  width:100%;
                  height:50px;
                  overflow:hidden;
                  display:flex;
                  align-items:center;
                  justify-content: center;
                  white-space:normal;
                  word-break:break-all;
              }
          }
          `
  let div = document.createElement('div')
  div.innerHTML = resultDom
  div.setAttribute('id', 'print_area')
  div.setAttribute('class', 'printDom')
  document.body.appendChild(div)
  printJs({
      printable: 'print_area',
      type: 'html',
      style: style,// 亦可使用引入的外部css;
      scanStyles: false
  })
  document.body.removeChild(document.querySelector('#print_area'))
 
}



/**
 *
 * @param {*} dataSource
 * @param {*} productData
 * @param {boolean} flag  是否限时优惠价信息
 */
export function toPrint(dataSource, productData, flag) {
  console.log(productData);
  let table = "";
  productData.forEach((item, index) => {
    table += `<tr>
            <td>${index + 1}</td>
            <td>${item.materialName ?? item.goodsName}${item.giftId !== "0" ? "（赠）" : ""
      }</td>
            <td>${item.sku} </td>
            <td>${item.orderProductCount}</td>
            <td>${(item.orderPrice / 100).toFixed(2)}</td>
            ${flag
        ? //  `<td>${(item.orderPriceTotal / 100).toFixed(2)}</td>`+
        //  `<td>${(item.detailDiscountsPrice / 100).toFixed(2)}</td>`+
        `<td>${(item.detailPayPrice / 100).toFixed(2)}</td>`
        : " "
      }
        </tr>`;
  });
  let dom = `

                <h2 class='title'>出货单</h2>
                <img src="${logo}" alt="" class="logo" />
                <div class="info">
                    <div class="orderCode orderInfo">
                        <span class="label">订单编号：</span>
                        <span class="val">${dataSource.orderCode}</span>
                    </div>
                    <div class="orderTime orderInfo">
                        <span class="label">订单时间：</span>
                        <span class="val">${dataSource.createTime}</span>
                    </div>
                    <div class="storeName orderInfo">
                        <span class="label">商户名：</span>
                        <span class="val">${dataSource.storeName ? dataSource.storeName : ""
    }</span>
                    </div>
                    <div class="userInfo orderInfo">
                        <span class="label">客户信息：</span>
                        <span class="val">${dataSource.memberName
      ? makeCode(
        dataSource.memberName,
        "mid",
        1,
        dataSource.memberName.length - 1
      )
      : ""
    }，${dataSource.memberPhone ? makeCode(dataSource.memberPhone, "mid", 3, 7) : ""
    }</span>
                    </div>
                    <div class="address orderInfo">
                        <span class="label">收货信息：</span>
                        <span class="val">${dataSource.memberAddress
      ? dataSource.memberAddress
      : ""
    }</span>
                    </div>
                    <div class="goodsInfo">
                        <table border='1' cellPadding='10' cellSpacing='0'>
                            <thead>
                                <tr>
                                    <td>序号</td>
                                    <td>物料名称(商品名)</td>
                                    <td>规格</td>
                                    <td>数量</td>
                                    <td>单价</td>
                                    ${flag
      ? //  '<td>原价</td>'+
      // '<td>优惠金额</td>'+
      "<td>实付价</td>"
      : " "
    }
                                </tr>
                            </thead>
                            <tbody>
                               ${table}
                                <tr>
                                    <td colSpan="1">合计</td>
                                    <td>￥${(
      dataSource.orderTotalPrice / 100
    ).toFixed(2)}</td>
                                    <td colSpan="${flag ? 3 : 2}">实付金额</td>
                                    <td>￥${(
      dataSource.orderPayPrice / 100
    ).toFixed(2)}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="footer">
                    <div class="thanks">感谢您选择哈奇马宠物！</div>
                    <div class="tips">
                        <div class="tipsTitle">温馨提示：</div>
                        <div class="tipsText">
                        遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！
                        </div>
                    </div>
                </div>
          `;
  let style = `@page { margin: 0; } body { padding: 0px;}
            .printDom {
                position: relative;
                padding: 20px 20px 10px;
                background-color: aqua;
            
            }
            
            .printDom .logo {
                width: 150px;
                background-color: #000;
                position: absolute;
                left: 50px;
                top: 20px;
                color:#00;
            }
            
            .printDom .title {
                font-weight: 600;
                font-size: 32px;
                text-align: center;
            }
            
            .printDom .orderInfo {
                display: flex;
                align-items: center;
                font-size: 14px;
                letter-spacing: 2px;
            
            }
            
            .printDom .orderInfo .label {
                display: flex;
                width: 80px;
            }
            
            .printDom table {
                width:90%;
                margin-top: 4px;
            
            }
            
            .printDom table td {
                padding: 5px 20px;
                font-size: 14px;
                text-align: center;
            }
            
            .footer {
                font-size: 16px;
                margin-top: 4px;
            
            }
            
            .printDom .footer .thanks {
                text-align: left;
            }
            
            .printDom .footer .tips {
                text-align: left;
            
            }
            
            .printDom .footer .tipsText {
                font-weight: 600;
            }`;
  let div = document.createElement("div");
  div.innerHTML = dom;
  div.setAttribute("id", "print_area");
  div.setAttribute("class", "printDom");
  document.body.appendChild(div);
  printJs({
    printable: "print_area",
    type: "html",
    style: style, // 亦可使用引入的外部css;
    scanStyles: false,
  });
  document.body.removeChild(document.querySelector("#print_area"));
}
//合并发货打印面单
export function mergePrints(dataSource, flag) {
  console.log(dataSource);
  let div = document.createElement("div");
  let body = "";
  let pageNo = 1;
  let pageTotal = 1;
  let totalHeight = 900
  dataSource.forEach((item,index)=>{
    let table = "";
    let clear = '';
    totalHeight = totalHeight-250
    if(totalHeight < 200){
      totalHeight = 900
      console.log(index);
      body +=`<div class='clear' ></div>`
    }
    item.orderDetailList.forEach((item2, index2) => {
      totalHeight = totalHeight-50
      let arr = JSON.parse(item2.goodsSkuJson);
      table += `<tr>
              <td><div class='tdHeight'>${index2 + 1}</div></td>
              <td><div class='tdHeight'>${item2.materialName ?? item2.goodsName}${
        item2.giftId !== "0" ? "（赠）" : ""
      }</div></td>
              <td><div class='tdHeight'>${arr.hasOwnProperty("skuAttribute") &&
              arr.skuAttribute.map((j) => {
                return j.value;
              })} </div></td>
              <td><div class='tdHeight'>${item2.orderProductCount}</div></td>
              <td><div class='tdHeight'>${(item2.orderPrice / 100).toFixed(2)}</div></td>
              ${
                flag
                  ? //  `<td>${(item.orderPriceTotal / 100).toFixed(2)}</td>`+
                    //  `<td>${(item.detailDiscountsPrice / 100).toFixed(2)}</td>`+
                    `<td><div class='tdHeight'>${(item2.detailPayPrice / 100).toFixed(2)}</div></td>`
                  : " "
              }
          </tr>`;
      
    })
    body +=`${clear}<div class="info">
              <div class='orderContent'>
                <div class="orderCode orderInfo">
                    <span class="label">订单编号：</span>
                    <span class="val">${item.orderCode}</span>
                </div>
                <div class="orderTime orderInfo">
                    <span class="label">订单时间：</span>
                    <span class="val">${item.createTime}</span>
                </div>
                <div class="storeName orderInfo">
                    <span class="label">商户名：</span>
                    <span class="val">${
                      item.storeName ? item.storeName : ""
                    }</span>
                </div>
                <div class="userInfo orderInfo">
                    <span class="label">客户信息：</span>
                    <span class="val">${
                      item.memberName
                        ? makeCode(
                          item.memberName,
                            "mid",
                            1,
                            item.memberName.length - 1
                          )
                        : ""
                    }，${
                      item.memberPhone ? makeCode(item.memberPhone, "mid", 3, 7) : ""
                    }</span>
                </div>
                <div class="address orderInfo">
                    <span class="label">收货信息：</span>
                    <span class="val">${
                      item.memberAddress
                        ? item.memberAddress
                        : ""
                    }</span>
                </div>
              </div>
              <div class="goodsInfo">
                  <table border='0' cellPadding='10' cellSpacing='0'>
                      <thead>
                          <tr>
                              <td><div class='tdHeight'>序号</div></td>
                              <td><div class='tdHeight'>物料名称(商品名)</div></td>
                              <td><div class='tdHeight'>规格</div></td>
                              <td><div class='tdHeight'>数量</div></td>
                              <td><div class='tdHeight'>单价</div></td>
                              ${
                                flag
                                  ? //  '<td>原价</td>'+
                                    // '<td>优惠金额</td>'+
                                    "<td><div class='tdHeight'>实付价</div></td>"
                                  : " "
                              }
                          </tr>
                      </thead>
                      <tbody>
                        ${table}
                          <tr>
                              <td colSpan="1"><div class='tdHeight'>合计</td>
                              <td><div class='tdHeight'>￥${(
                                item.orderTotalPrice / 100
                              ).toFixed(2)}</div></td>
                              <td colSpan="${flag ? 3 : 2}"><div class='tdHeight'>实付金额</div></td>
                              <td><div class='tdHeight'>￥${(
                                item.orderPayPrice / 100
                              ).toFixed(2)}</div></td>
                          </tr>
                          <tr>
                          <td colSpan="1"><div class='tdHeight'>合计</td>
                          <td><div class='tdHeight'>￥${(
                            item.orderTotalPrice / 100
                          ).toFixed(2)}</div></td>
                          <td colSpan="${flag ? 3 : 2}"><div class='tdHeight'>实付金额</div></td>
                          <td><div class='tdHeight'>￥${(
                            item.orderPayPrice / 100
                          ).toFixed(2)}</div></td>
                      </tr>
                      <tr>
                          <td colSpan="1"><div class='tdHeight'>合计</td>
                          <td><div class='tdHeight'>￥${(
                            item.orderTotalPrice / 100
                          ).toFixed(2)}</div></td>
                          <td colSpan="${flag ? 3 : 2}"><div class='tdHeight'>实付金额</div></td>
                          <td><div class='tdHeight'>￥${(
                            item.orderPayPrice / 100
                          ).toFixed(2)}</div></td>
                      </tr>
                      <tr>
                          <td colSpan="1"><div class='tdHeight'>合计</td>
                          <td><div class='tdHeight'>￥${(
                            item.orderTotalPrice / 100
                          ).toFixed(2)}</div></td>
                          <td colSpan="${flag ? 3 : 2}"><div class='tdHeight'>实付金额</div></td>
                          <td><div class='tdHeight'>￥${(
                            item.orderPayPrice / 100
                          ).toFixed(2)}</div></td>
                      </tr>
                      </tbody>
                    </table>
                  </div>
                </div>`
  })
  console.log(totalHeight);
  let dom = `
              <div class='header'>
                <h2 class='title'>出货单</h2>
                <img src="${logo}" alt="" class="logo" />
              </div>
                ${body}
                <div class="footer">
                    <div class="thanks">感谢您选择哈奇马宠物！</div>
                    <div class="tips">
                        <div class="tipsTitle">温馨提示：</div>
                        <div class="tipsText">
                        遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！
                        </div>
                    </div>
                </div>
                <div class='pageNo'>
                ${pageNo+'/'+pageTotal}
                </div>
          `;
    console.log(dom);
  let style = `@page {} body {padding:20px;}
            .printDom {
                position: relative;
                padding: 0px 0px 10px;
                background-color: aqua;
            
            }
            
            .printDom .logo {
                width: 150px;
                background-color: #000;
                position: absolute;
                left: 50px;
                top: 20px;
                color:#00;
            }
            .printDom .header {
              width:100%;
              height:100px;
          }
            .printDom .title {
                font-weight: 600;
                font-size: 32px;
                text-align: center;
            }
            
            .printDom .orderInfo {
                display: flex;
                height:20px;
                align-items: center;
                font-size: 14px;
                line-height:20px;
                letter-spacing: 2px;
            }
             .orderContent {
              border: none;
              height:100px;
          }
            .printDom .orderInfo .label {
                display: flex;
                width: 80px;
            }
            
            .printDom table {
                width:100%;
                margin:auto;
                margin-top: 4px;
                margin-bottom:10px;
            }
            .printDom .tdHeight {
              height:48px;
          }
            .printDom table td {
                border: 1px solid black;
                padding: 0px 20px;
                font-size: 14px;
                line-height:20px;
                text-align: center;
            }
            
            .footer {
                font-size: 16px;
                margin-top: 4px;
            
            }
            
            .pageNo{
              position:fixed;
              bottom:0;
              right:0;
            }
            .printDom .footer .thanks {
                text-align: left;
            }
            
            .printDom .footer .tips {
                text-align: left;
            
            }
            .clear {
              page-break-after: always;
            }
            
            .printDom .footer .tipsText {
                font-weight: 600;
            }`;
  
  div.innerHTML = dom;
  div.setAttribute("style", "");
  div.setAttribute("id", "print_area");
  div.setAttribute("class", "printDom");
  document.body.appendChild(div);
  printJs({
    printable: "print_area",
    type: "html",
    style: style, // 亦可使用引入的外部css;
    scanStyles: false,
    repeatTableHeader:false
  });
  document.body.removeChild(document.querySelector("#print_area"));
}
/*
 * tag：所要创建的标签名称
 * attrs: 所需要添加的属性，｛key:val,key:val｝
 */
function makeSVG(tag, attrs) {
  const ns = "http://www.w3.org/2000/svg";
  const xlinkns = "http://www.w3.org/1999/xlink";

  let el = document.createElementNS(ns, tag);
  if (tag === "svg") {
    el.setAttribute("xmlns:xlink", xlinkns);
  }
  for (let k in attrs) {
    if (k === "xlink:href") {
      el.setAttributeNS(xlinkns, k, attrs[k]);
    } else {
      el.setAttribute(k, attrs[k]);
    }
  }
  return el;
}
export function printWaybill(dataSource, sku) {
  console.log(dataSource, "dataSource");
  let svg = makeSVG("svg", { id: "barCodeSvg" });
  JsBarcode(svg, dataSource.orderCode, {
    displayValue: false,
    width: 2,
    height: 50,
    margin: 0,
  });

  let dom = document.createElement("div");
  dom.setAttribute("class", "waybill");
  dom.setAttribute("id", "barcode");

  dom.innerHTML = `
            <div class="code">${dataSource.orderCode}</div>
            <img src="${logo}" alt="" class="logo" />
            <div class="recipient ">
                <div class="value">
                <div class="name">商户名：</div><div class="txt">${dataSource.storeName
    }</div>
                </div>
                <div class="value">
                <div class="name">客户信息：</div> <div class="txt">${makeCode(
      dataSource.memberName,
      "mid",
      1,
      dataSource.memberName.length - 1
    )}，${makeCode(dataSource.memberPhone, "mid", 3, 7)}</div>
                </div>
                <div class="value">
                <div class="name">收货信息：</div><div class="txt">${dataSource.memberAddress
    }</div>
                </div>
            </div>
            <div class="sku">
                <div class="value"> 
                
                <div class="name">商品明细：</div>
                    <div class="txt">
                    ${sku.join("</br>")}
                    </div>
                </div>
            </div>
            <div class="flag">宠圈顶配，养宠必备</div>
            <div class="tips">哈奇马温馨提示:</div>
            <div class="tipTxt">遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！</div>
            <img src="${wxGong}" alt="" class="wxGong" />
      `;
  let canvas = document.createElement("canvas");
  const XML = new XMLSerializer().serializeToString(svg);
  const SVG64 = btoa(XML);
  const image64 = "data:image/svg+xml;base64," + SVG64;
  const img = new Image();
  img.onload = function () {
    canvas.getContext("2d").drawImage(img, 0, 0);
  };
  img.src = image64;
  img.setAttribute("class", "img");
  dom.prepend(img);
  document.body.appendChild(dom);
  let style = `@page { margin: 0; } body { padding: 0px;}
    body { padding: 0px}
    .waybill{
        width:95%;
        font-size:12px;
        position:relative;
    }
    .code{
        text-align: center;
        margin-bottom:0;
        font-size:12px;
    }
    .img{
        width:80%;
        margin:0 0 0 10%;                        
    }
    .wxGong{
        width:80px;
        height:80px;
        position:absolute;
        right:20px;
        bottom:40px;
    }
     .logo {
        width: 60px;
        background-color: #000;
        color:#00;
        margin-left:20px;
    }
    .recipient,.sku{
        border-top:1px dashed #000;
        border-left:1px dashed #000;
        border-right:1px dashed #000;
        border-bottom:1px dashed #000;

        padding:10px 0;
    }
    
    
    .recipient .value,.sku .value{
        padding:0 10px;
        display:flex;
        justify-content:space-between;
    }
    .recipient .value .name,.sku .value .name{
        width:70px;
    }
    .recipient .value .txt,.sku .value .txt{
        width:calc(100% - 75px);
    }
    .flag{
        font-weight:600;
        margin:20px 0 40px;

    }
    .tipTxt{
        font-weight:600;
        

    }
    .sku{
        border-bottom:1px dashed #000;
        display:none;
    }
                `;
  setTimeout(() => {
    printJs({
      printable: "barcode",
      type: "html",
      style: style, // 亦可使用引入的外部css;
      scanStyles: false,
    });
    document.body.removeChild(document.querySelector("#barcode"));
  }, 0);
}

export function printLogo() {
  const dom = `<img src="${NewLogo}" alt="" class="logo1" /><img src="${NewLogo}" alt="" class="logo2" />`;
  let div = document.createElement("div");
  div.innerHTML = dom;
  div.setAttribute("id", "print_area");
  div.setAttribute("class", "printDom");
  document.body.appendChild(div);
  printJs({
    printable: "print_area",
    type: "html",
    style: `
                @page { margin: 0;size:portrait ;count:100} 
                body { padding: 0px;position:relative;}
                .logo1{position:absolute;width:100px;height:120px;left:-5px;top:220px}
                .logo2{position:absolute;width:100px;height:120px;left:-5px;top:50px}
                `, // 亦可使用引入的外部css;
    scanStyles: false,
  });
}
